//
//  HRZShoppingCartViewController.m
//  EMarket
//
//  Created by 石头 on 2018/5/13.
//  Copyright © 2018年 好日子. All rights reserved.
//

#import "HRZShoppingCartViewController.h"

// Controllers
#import "HRZConfirmOrderViewController.h"
#import "HRZStoreViewController.h"
// Models
#import "HRZStoreModel.h"
#import "HRZCartGoodsDetailModel.h"
// Views
#import "HRZShoppingCartGoodsCell.h"
#import "HRZShoppingCartCountView.h"

#import "HRZShoppingCartHeaderView.h"

#import "HRZNumberOfChoiesView.h"
// Vendors
#import <MJExtension/MJExtension.h>
// Categories

// Others
#import "HRZGlobalNetManager.h"

#define kBottomHeight       50

@interface HRZShoppingCartViewController ()<UITableViewDelegate, UITableViewDataSource, HRZShoppingCartGoodsCellDelegate>

@property (nonatomic, strong) HRZCartModel *mCartModel;
@property (nonatomic, strong) HRZShoppingCartCountView *mCountView;

@end


static NSString * const HRZShoppingCartHeaderViewId    = @"HRZShoppingCartHeaderViewId";
static NSString * const HRZShoppingCartGoodsCellId      = @"HRZShoppingCartGoodsCellId";
static NSString * const HRZShoppingCartBottomViewId    = @"HRZShoppingCartBottomViewId";

@implementation HRZShoppingCartViewController

#pragma mark - LifeCyle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
    self.navigationItem.title = @"购物车";
    
    
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.mCountView];
    
    [self setUpTableView];
    
//    [self setupData];
    [self demoData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
//    self.tableView.mj_header.refreshing = NO;

}

#pragma mark - Public

#pragma mark - Private

/** 获取数据 */
- (void)setupData {
    [[HRZGlobalNetManager getGlobalNetManager] onSearchCartGoodsListByCurrentShopComplete:^(NSArray *array, BOOL isSuc) {
        if (isSuc) {
            
        }
        
        [self.tableView reloadData];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSInteger count = _mCartModel.storeModels.count;
    return count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    HRZCartStoreModel *cartStore = _mCartModel.storeModels[section];
    
    NSInteger count = cartStore.cartGoods.count;
    return count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HRZCartStoreModel *cartStore = _mCartModel.storeModels[indexPath.section];
    
    /** 获取cell */
    HRZShoppingCartGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:HRZShoppingCartGoodsCellId];
    
    /** cell的数据model */
    HRZCartGoodsDetailModel *goodsModel = cartStore.cartGoods[indexPath.row];
    cell.model = goodsModel;
    cell.delegate = self;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kFit(80);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kFit(50);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    /** 生成头view */
    HRZShoppingCartHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HRZShoppingCartHeaderViewId];
    headerView.contentView.backgroundColor = [UIColor whiteColor];

    /** 绑定store信息 */
    headerView.storeModel = _mCartModel.storeModels[section].storeModel;

    /** 点击事件 */
    WS(weakSelf);
    //点击全选
    headerView.ClickBlock = ^(BOOL isClick) {
        SS(strongSelf);
        strongSelf.mCartModel.storeModels[section].storeModel.isSelect = isClick;
        for (HRZCartGoodsDetailModel *goodsModel in _mCartModel.storeModels[section].cartGoods) {
            goodsModel.isSelect = isClick;
        }
        [strongSelf.tableView reloadData];
        [strongSelf countAllPrice];
    };
    
    //点击到门店
    headerView.StoreBlock = ^(HRZStoreModel *model) {
        SS(strongSelf);
        
        HRZStoreViewController *storeVC = [[HRZStoreViewController alloc] init];
        storeVC.storeModel = model;
        
        [strongSelf.navigationController pushViewController:storeVC animated:YES];
    };


    return headerView;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定删除?" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        WEAKSELF
        /** 确认删除 */
        [alert addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [weakSelf deleteGoodsWithIndexPath:indexPath];
            
        }]];
        /** 取消删除 */
        [alert addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        
        
    }
}
#pragma mark - ----  ScrollViewDelegate  ----
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.tableView == scrollView) {
        CGFloat sectionHeaderHeight = 50;
        if (scrollView.contentOffset.y <= sectionHeaderHeight && scrollView.contentOffset.y >= 0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y>=sectionHeaderHeight){
           scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}
#pragma mark - ----  HRZCellDelegate  ----
- (void)onShoppingCartGoodsCell:(HRZShoppingCartGoodsCell *)cell changeModel:(HRZCartGoodsDetailModel *)model {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
//    [self.mGoodsArray replaceObjectAtIndex:indexPath.row withObject:model];
    [self.tableView reloadData];
    [self judgeIsAllSelect];
    [self countAllPrice];
}

#pragma mark -------------- Action Logic--------------

/** 判断所有商品是否全选 */
- (void)judgeIsAllSelect {
    NSInteger count = _mCartModel.storeModels.count;
    NSInteger selCount = 0;
    
    // 遍历购物车商品，的到商品数量
    for (HRZCartStoreModel *model in _mCartModel.storeModels) {
        if (model.storeModel.isSelect) {
            selCount += 1;
        }
    }
    
    //  如果购物车总商品数量等于选择商品数量，则表示全选
    if (count == selCount) {
        self.mCountView.isAllSelectd = YES;
    } else {
        self.mCountView.isAllSelectd = NO;
    }
}

/** 计算总价格 */
- (void)countAllPrice {
    double totalPrice = 0.0;
    for (HRZCartStoreModel *storeModel in _mCartModel.storeModels) {
        
        for (HRZCartGoodsDetailModel *goodsModel in storeModel.cartGoods) {
            if (goodsModel.isSelect) {
                double price = [goodsModel.price doubleValue];
                totalPrice += price * [goodsModel.goodsNumber integerValue];
            }
        }
    }
    self.mCountView.totalPrice = [NSString stringWithFormat:@"%.2f", totalPrice];
}

#pragma mark -------------- Action Click--------------


/** 点击全选 */
- (void)clickAllSelectdButton:(BOOL)isAllSelected{
    
    if (isAllSelected) {  // 选中后，所有门店选中，门店的商品选中
        for (HRZCartStoreModel *cartStoreModel in _mCartModel.storeModels) {
            cartStoreModel.storeModel.isSelect = YES;
            for (HRZCartGoodsDetailModel *goodsModel in cartStoreModel.cartGoods) {
                goodsModel.isSelect = YES;
            }
        }
    } else {
        for (HRZCartStoreModel *cartStoreModel in _mCartModel.storeModels) {
            cartStoreModel.storeModel.isSelect = NO;
            for (HRZCartGoodsDetailModel *goodsModel in cartStoreModel.cartGoods) {
                goodsModel.isSelect = NO;
            }
        }
    }
    
    [self.tableView reloadData];
    [self countAllPrice];
}

/** 直接生成下单 */
- (void)onCountButtonClick {
    
//    [[HRZGlobalNetManager getGlobalNetManager] onCreateOrderWithCartGoods:nil complete:^(NSString *result, BOOL isSuc) {
//        NSLog(@"%@", result);
//    }];
//
//
//    return ;
    HRZConfirmOrderViewController *confOrder = [HRZConfirmOrderViewController new];
    
    [self.navigationController pushViewController:confOrder animated:YES];
}

/** 删除某个商品 */
- (void)deleteGoodsWithIndexPath:(NSIndexPath *)indexPath {
    
    /** 门店模型 */
    HRZCartStoreModel *storeModel = _mCartModel.storeModels[indexPath.section];
    
    /** 商品模型 */
    HRZCartGoodsDetailModel *goodsModel = storeModel.cartGoods[indexPath.item];
    
    [[HRZGlobalNetManager getGlobalNetManager] deletedCartGoodsId:goodsModel.goodsId complete:^(BOOL isSuc) {
        
    } ];
    
    
    /** tableview 移除商品行 */
    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    
    /** 判断商品是否全选 */
    [self judgeIsAllSelect];
    
    /** 更新界面 */
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.tableView reloadData];
    });
}

- (void)demoData {
    
    NSMutableArray *array = [HRZCartStoreModel mj_objectArrayWithFilename:@"Carts.plist"];

//    self.mCartModel = cartModel;
    HRZCartModel *model = [[HRZCartModel alloc] init];
    model.storeModels = array;
    
    self.mCartModel = model;
    
    [self.tableView reloadData];
}

#pragma mark - Getter/Setter
- (HRZShoppingCartCountView *)mCountView{
    if (!_mCountView) {
        _mCountView = [[HRZShoppingCartCountView alloc] initWithFrame:CGRectMake(0, KScreenHeight - kBottomHeight - kTopHeight - kTabBarHeight, KScreenWidth, kBottomHeight)];
        _mCountView.backgroundColor = [UIColor lightGrayColor];
        _mCountView.totalPrice = @"0.0";
        
        WEAKSELF
        _mCountView.AllClickBlock = ^(BOOL isAll) {
            [weakSelf clickAllSelectdButton:isAll];
        };
        _mCountView.AccountBlock = ^{
            [weakSelf onCountButtonClick];
        };
    }
    return _mCountView;
}

- (void)setUpTableView {
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    CGRect tableFrame = self.tableView.frame;
    tableFrame.size.height = KScreenHeight - kTopHeight - kTabBarHeight - kBottomHeight;
    self.tableView.frame = tableFrame;
    [self.tableView registerClass:[HRZShoppingCartGoodsCell class] forCellReuseIdentifier:HRZShoppingCartGoodsCellId];
    [self.tableView registerClass:[HRZShoppingCartHeaderView class] forHeaderFooterViewReuseIdentifier:HRZShoppingCartHeaderViewId];
}

@end
